package com.frank.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/3/23
 * @description 登录拦截器
 */
@Component
public class LoginFilter implements GlobalFilter {

    private final List<String> excludePathList = Arrays.asList("/auth/user/doLogin");

    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String path = request.getURI().getPath();
        if (excludePathList.contains(path)) {
            chain.filter(exchange);
        }
        boolean login = StpUtil.isLogin();
        if (!login) {
            return chain.filter(exchange.mutate().request(mutate.build()).build());
        }
        String loginId = StpUtil.getLoginIdAsString();
        if (StringUtils.isBlank(loginId)) {
            throw new Exception("未找到用户信息");
        }
        mutate.header("loginId", loginId);
        // 将更新好的 mutate 对象重新 Build 到 exchange 中
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
